from odoo import models, api
import threading


class SbMESJob(models.Model):
    _inherit = 'hr.job'

    def cron_all(self):
        index = 1
        records = self.env['hr.job'].sudo().search([])
        index = 1
        for x in records:
            x.write({'s_code': 'WTT%04d' % index})
            index += 1

        for rec in records:
            rec.job_upload_mes()

    @api.model_create_multi
    def create(self, vals_list):
        result = super().create(vals_list)
        mes_enabled = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.enabled')], limit=1).s_value
        if mes_enabled:
            for rec in result:
                rec.with_delay().job_upload_mes()
        return result

    def write(self, vals):
        res = super().write(vals)
        mes_enabled = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.enabled')], limit=1).s_value
        if mes_enabled:
            self.with_delay().job_upload_mes()
        return res

    def job_upload_mes(self):
        """
        岗位信息
        """
        job_list = []
        for record in self:
            if not record.s_code:
                continue
            bs_post_rgop = [  # 暂无职位等级
                # {
                #     "seq": 0,
                #     "gop_code": "string",
                #     "up_qty": 0,
                #     "remark": "string"
                # }
            ]
            job_list.append({
                "org_id": "0001",
                "ps_code": record.s_code,  # 岗位编码
                "ps_name": record.name,  # 岗位名称
                "is_pli": "N",  # 责任人岗位 N:非责任人岗位 Y:是责任人岗位
                "is_spe": "N",  # 特殊岗位 N:非责任人岗位 Y:是特殊岗位
                "dept_code": record.department_id.code or '',  # 部门编码
                "parent_code": "",  # 上级岗位编码
                "vb_time": "",  # 有效开始时间
                "ve_time": "",  # 有效结束时间
                "std_pnum": 0,  # 编制人数
                "is_psover": "N",  # 超编 N:非超编 Y:是超编
                "cur_pnum": 0,  # 目前在编人数
                "gop_code": "",  # 最低上岗职等
                "is_valid": "Y",  # 启用状态
                "remark": "",  # 备注
                "bs_post_rgop": bs_post_rgop  # 岗位职等表
            })
        data = {
            "docType": "BS_POST",
            "updateType": "UPDATE",
            "data": job_list
        }
        self.env['s.mes.upload'].upload_data(data)
